package net.keebook.webapp.bean;

import java.util.Locale;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;

import net.keebook.webapp.dao.UserDao;
import net.keebook.webapp.entity.User;
import net.keebook.webapp.model.SessionModel;

@ManagedBean
@SessionScoped
public class LanguageBean {
	@Inject
	private UserDao userDao;
	
	public void setLocaleCode(String language, String country) {
		SessionModel sessionModel = SessionModel.getInstance(FacesContext.getCurrentInstance());
		
		Locale locale = new Locale(language, country);
		FacesContext.getCurrentInstance().getViewRoot().setLocale(locale);
		sessionModel.setLocale(locale);
		
		// Store locale in session's user
		if (sessionModel.getLoggedIn()) {
			User user = getUserDao().get(sessionModel.getUserId());
			if (user != null) {
				user.setLanguage(language);
				user.setCountry(country);
				getUserDao().update(user);
			}
		}
	}

	public Locale getLocale() {
		SessionModel sessionModel = SessionModel.getInstance(FacesContext.getCurrentInstance());
		return sessionModel.getLocale();
	}

	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}
}
